package cn._51doit.flink.day02.sources;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;

import java.util.Random;

/**
 * 自定义Source（非并行的Source）
 *
 * 仅仅实现了SourceFunction，那么该Source就是一个非并行的Source，即只有一个并行度
 * 如果Source的run方法产生数据，该方法一直运行不退出，该Source就是一个无限的数据流
 *
 */
public class CustomSource2 {

    public static void main(String[] args) throws Exception {

        Configuration configuration = new Configuration();
        configuration.setInteger("rest.port", 8081);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(configuration);

        DataStreamSource<Integer> nums = env.addSource(new SourceFunction<Integer>() {

            boolean flag = true;

            @Override
            public void run(SourceContext<Integer> ctx) throws Exception {
                System.out.println("run method invoked ~~~~~~~");
                Random random = new Random();
                while (flag) {
                    //输出数据
                    Thread.sleep(1000);
                    ctx.collect(random.nextInt(100));
                }
            }

            @Override
            public void cancel() {
                flag = false;
                System.out.println("cancel method invoked !!!!!");
            }
        });


        System.out.println("实现SourceFunction自定义的Source的并行度: " + nums.getParallelism());
        nums.print();
        env.execute();



    }
}
